package com.liucxu.qiushimeinv.Utils;

import com.liucxu.qiushimeinv.Consts.Consts;
import com.orhanobut.logger.Logger;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Retrofit以及RxJava网络请求的类
 * Created by liukanshan on 2017/1/1.
 */

public class ServiceFactory {

    private static ServiceFactory instance;

    public static ServiceFactory GetInstance() {
        synchronized (ServiceFactory.class) {
            if (instance == null) {
                instance = new ServiceFactory();
            }
        }
        return instance;
    }

    public <S> S createService(Class<S> serviceClass) {
        Retrofit.Builder builder = new Retrofit.Builder();
        Retrofit retrofit = builder.baseUrl(Consts.BASE_URL).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).addConverterFactory(GsonConverterFactory.create()).client(getHttpClient()).build();
        return retrofit.create(serviceClass);
    }

    private OkHttpClient getHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(10, TimeUnit.SECONDS).readTimeout(10, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS).addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                okhttp3.Request request = chain.request();
                Logger.d("Sending request %s on %s%n%s,body%s", request.url(), chain.connection(), request.headers(), request.body());
                Response originalResponse = chain.proceed(request);
                String response_str = originalResponse.body().string();
                Logger.json(response_str);
                return originalResponse.newBuilder().body(ResponseBody.create(MediaType.parse("UTF-8"), response_str)).build();
            }
        });
        return builder.build();
    }
}
